import React, {useState} from 'react';
import {useDispatch, useSelector} from 'react-redux'; // Assuming you use useSelector to get user info
import {Box, Card, CardContent, CardHeader, Tab, Tabs, TextField, Typography} from '@mui/material';
import {TabContext, TabPanel} from '@mui/lab';

import LoadingButton from "@mui/lab/LoadingButton";
import CircularProgress from "@mui/material/CircularProgress";

import {setUser} from '../redux/store';
import {update} from "../api/common/user-info";
import {alert} from "./common/alert";

function TabPanelWrapper({children, value, index}) {
    return (<TabPanel value={value} index={index}>{children}</TabPanel>);
}

const UserField = ({label, value}) => (
    <Box display="flex" gap={2}>
        <Typography variant="body1" sx={{width: '64px', textAlign: 'right'}}>{label}</Typography>
        <Typography variant="body1">{value}</Typography>
    </Box>
);

const UserDetail = ({user}) => (
    <Box display="flex" gap={1} flexDirection="column">
        <UserField label="用户 ID" value={user?.id}/>
        <UserField label="登录 ID" value={user?.loginId}/>
        <UserField label="姓名" value={user?.name}/>
        <UserField label="学校" value={user?.school}/>
    </Box>
);

function Userinfo() {

    const user = useSelector(state => state.auth.user);

    // type===1: update name, type===2: update password
    const [type, setType] = useState(0);

    const [name, setName] = useState(user?.name);

    const [currentPassword, setCurrentPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');

    const [tabValue, setTabValue] = useState('1');
    const [loading, setLoading] = useState(false);

    const dispatch = useDispatch();

    const handleChange = (event, newValue) => {
        setTabValue(newValue);
    };

    const handleInputChange = (event) => {
        const {name, value} = event.target;
        switch (name) {
            case 'name':
                setName(value);
                break;
            case 'currentPassword':
                setCurrentPassword(value);
                break;
            case 'newPassword':
                setNewPassword(value);
                break;
            case 'confirmPassword':
                setConfirmPassword(value);
                break;
            default:
                break;
        }
    };

    const submitName = async (event) => {
        setType(1);
        await handleSubmit(event, 1);
    }
    const submitPassword = async (event) => {
        setType(2);
        await handleSubmit(event, 2);
    }

    const handleSubmit = async (event, type) => {
        event.preventDefault();

        if (type === 2 && newPassword !== confirmPassword) {
            alert("新密码和确认密码不匹配", "error");
            return;
        }

        setLoading(true);
        update(type === 1 ? {type, name} : {type, password: currentPassword, newPassword})
            .then(data => {
                if (data) {
                    if (type === 1) {
                        dispatch(setUser({...user, name}));
                    }
                    alert("用户信息更新成功");
                }
            });

        setType(0);
        setLoading(false);
    }

    return (
        <Box p={4}>

            <Box display="flex" gap={4} alignItems="flex-start" flexWrap="wrap">
                <Card raised sx={{width: '30%', padding: 2, boxSizing: 'border-box', minWidth: '320px'}}>
                    <CardHeader title="用户信息"/>
                    <CardContent>
                        <UserDetail user={user}/>
                    </CardContent>
                </Card>

                <Card raised sx={{width: '40%', padding: 3, boxSizing: 'border-box', minWidth: '320px'}}>
                    <CardHeader title="修改资料"/>

                    <TabContext value={tabValue}>
                        <Box sx={{borderBottom: 1, borderColor: 'divider'}}>
                            <Tabs value={tabValue} onChange={handleChange} aria-label="user info tabs">
                                <Tab label="基本信息" value="1"/>
                                <Tab label="密码" value="2"/>
                            </Tabs>
                        </Box>

                        {tabValue === "1" && (
                            <TabPanelWrapper value={tabValue} index="1">
                                <Box>
                                    <form onSubmit={submitName}>
                                        <TextField
                                            variant="outlined"
                                            margin="normal"
                                            required
                                            fullWidth
                                            label="名称"
                                            name="name"
                                            value={name}
                                            onChange={handleInputChange}
                                            autoFocus
                                            size="small"
                                        />
                                        <LoadingButton
                                            type="submit"
                                            disabled={loading}
                                            fullWidth
                                            variant="contained"
                                            color="primary"
                                            className="submit"
                                            size="large"
                                            sx={{marginTop: "16px"}}
                                            loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                                            loading={loading && type === 1}
                                        >
                                            提交
                                        </LoadingButton>
                                    </form>
                                </Box>
                            </TabPanelWrapper>)}
                        {tabValue === "2" && (
                            <TabPanelWrapper value={tabValue} index="2">
                                <Box>
                                    <form onSubmit={submitPassword}>
                                        <TextField
                                            variant="outlined"
                                            margin="normal"
                                            required
                                            fullWidth
                                            label="当前密码"
                                            name="currentPassword"
                                            value={currentPassword}
                                            type="password"
                                            onChange={handleInputChange}
                                            autoFocus
                                            size="small"
                                        />
                                        <TextField
                                            variant="outlined"
                                            margin="normal"
                                            required
                                            fullWidth
                                            label="新密码"
                                            name="newPassword"
                                            value={newPassword}
                                            type="password"
                                            onChange={handleInputChange}
                                            size="small"
                                        />
                                        <TextField
                                            variant="outlined"
                                            margin="normal"
                                            required
                                            fullWidth
                                            label="重复新密码"
                                            name="confirmPassword"
                                            value={confirmPassword}
                                            type="password"
                                            onChange={handleInputChange}
                                            size="small"
                                        />
                                        <LoadingButton
                                            type="submit"
                                            disabled={loading && type === 2}
                                            fullWidth
                                            variant="contained"
                                            color="primary"
                                            className="submit"
                                            size="large"
                                            sx={{marginTop: "16px"}}
                                            loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                                            loading={loading && type === 2}
                                        >
                                            提交
                                        </LoadingButton>
                                    </form>
                                </Box>
                            </TabPanelWrapper>)}
                    </TabContext>
                </Card>
            </Box>
        </Box>
    );
}

export default Userinfo;
